#include <iostream>
#include <vector>
#include <algorithm>

// 抽象主题
class Subject {
public:
    virtual void addObserver(class Observer* observer) = 0;
    virtual void removeObserver(class Observer* observer) = 0;
    virtual void notifyObservers() = 0;
};

// 抽象观察者
class Observer {
public:
    virtual void update(int data) = 0;
};

// 具体主题
class ConcreteSubject : public Subject {
private:
    int state;
    std::vector<Observer*> observers;

public:
    void addObserver(Observer* observer) override {
        observers.push_back(observer);
    }

    void removeObserver(Observer* observer) override {
        observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
    }

    // 类似触发器 
    void setState(int newState) {
        state = newState;
        notifyObservers();
    }

    void notifyObservers() override {
        for (Observer* observer : observers) {
            observer->update(state);
        }
    }
};

// 具体观察者,可以用在监听回调里面
class ConcreteObserver : public Observer {
public:
    void update(int data) override {
        std::cout << "Observer received update with data: " << data << std::endl;
    }
};

int main() {
    // 创建具体主题和观察者
    ConcreteSubject subject;
    ConcreteObserver observer1, observer2;

    // 添加观察者到主题
    subject.addObserver(&observer1);
    subject.addObserver(&observer2);

    // 改变主题状态，通知观察者
    subject.setState(42);

    // 移除一个观察者
    subject.removeObserver(&observer1);

    // 再次改变主题状态，通知剩余的观察者
    subject.setState(100);

    return 0;
}